package logic

import (
	"golang.org/x/crypto/bcrypt"
	"lisGin/lib"
	"lisGin/model"
	"lisGin/server"
)

type UserLogin struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

func (loginParams *UserLogin) Login() lib.Response {
	username := loginParams.Username
	userInfo := model.GetByUserName(username)
	if userInfo.ID == 0 {
		return lib.Fail(lib.PasswordErrorCode, lib.PasswordErrorMsg)
	}
	if err := bcrypt.CompareHashAndPassword([]byte(userInfo.Password), []byte(loginParams.Password)); err != nil {
		return lib.Fail(lib.PasswordErrorCode, lib.PasswordErrorMsg)
	}
	customerInfo := lib.CustomerInfo{
		Username: userInfo.Username,
	}
	// 生成token
	token, err := lib.CreateToken(server.AppSecretKey, customerInfo)
	if err != nil {
		return lib.Fail(lib.CreateTokenErrorCode, lib.CreateTokenErrorMsg)
	}

	data := map[string]interface{}{
		"username": userInfo.Username,
		"nickname": userInfo.Nickname,
		"token":    token,
	}

	return lib.Success(data)
}

type UserRegister struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
	Nickname string `json:"nickname" binding:"required"`
}

func (regParams *UserRegister) Register() lib.Response {
	bytes, err := bcrypt.GenerateFromPassword([]byte(regParams.Password), bcrypt.MinCost)
	if err != nil {
		panic(err)
	}
	var user = model.User{
		Username: regParams.Username,
		Password: string(bytes),
		Nickname: regParams.Nickname,
	}
	// 判断是否有相同的用户名
	hasUserInfo := model.GetByUserName(regParams.Username)
	if hasUserInfo.ID != 0 {
		return lib.Fail(lib.UserHasExistErrorCode, lib.UserHaseExistErrorMsg)
	}
	user.CreateUser()
	if user.ID == 0 {
		return lib.Fail(lib.CreateUserErrorCode, lib.CreateUserErrorMsg)
	}

	data := map[string]interface{}{
		"username": user.Username,
		"nickname": user.Nickname,
	}
	return lib.Success(data)
}
